package com.boot.common.except;

import com.boot.common.constant.MessageConstant;
import com.boot.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局系统异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用户名或密码错误
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result<?> usernameOrPasswordException(Exception e) {
        return Result.error(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
    }

    /**
     * 令牌已失效
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(InsufficientAuthenticationException.class)
    public Result<?> tokenExpireException(Exception e) {
        return Result.error(MessageConstant.TOKEN_EXPIRE);
    }

    /**
     * 用户已失效
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(DisabledException.class)
    public Result<?> userDisabledException(Exception e) {
        return Result.error(MessageConstant.USER_LOCKED);
    }

    /**
     * 用户已锁定
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(LockedException.class)
    public Result<?> userLockedException(Exception e) {
        return Result.error(MessageConstant.USER_LOCKED);
    }

    /**
     * 权限不足
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> permissionDeniedException(Exception e) {
        return Result.error(MessageConstant.PERMISSION_DENIED);
    }

    /**
     * 系统错误（其他错误）
     * @param e 异常
     * @return 错误结果
     */
    @ExceptionHandler(Exception.class)
    public Result<?> systemErrorException(Exception e) {
        return Result.error(MessageConstant.SYSTEM_ERROR);
    }

}
